type WorkerMessage<T = any> = {
    id: string; // 任务唯一标识
    type: 'task' | 'result' | 'error';
    data?: T;
    error?: Error;
};

type WorkerOptions = {
    scriptPath: string; // Worker脚本路径
    type?: 'module' | 'classic'; // 脚本类型（默认module）
    onError?: (error: Error) => void; // 全局错误回调
    onTerminate?: () => void; // 终止回调
};
function generateTaskId(): string {
    // 简单版 UUID（确保唯一性即可）
    return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
}
export class WorkerManager {
    private worker: Worker | null = null;
    private pendingTasks = new Map<string, { resolve: (data: any) => void; reject: (error: Error) => void }>();
    private isTerminated = false;
    private options: Required<WorkerOptions>;

    constructor(options: WorkerOptions) {
        this.options = {
            type: 'module',
            onError: () => { },
            onTerminate: () => { },
            ...options
        };
        this.initWorker();
    }

    // 初始化Worker
    private initWorker() {
        if (this.isTerminated) return;

        try {
            // 处理脚本路径（支持相对路径，基于当前模块）
            const srcBaseUrl = new URL('../../', import.meta.url).href;            
            const workerUrl = new URL(this.options.scriptPath, srcBaseUrl);
            this.worker = new Worker(workerUrl, { type: this.options.type });

            // 监听Worker消息
            this.worker.onmessage = (e: MessageEvent<WorkerMessage>) => {
                this.handleMessage(e.data);
            };

            // 监听Worker错误
            this.worker.onerror = (error) => {
                const err = new Error(`Worker执行错误: ${error.message}`);
                this.options.onError?.(err);
                // 拒绝所有未完成的任务
                this.pendingTasks.forEach(({ reject }) => reject(err));
                this.pendingTasks.clear();
            };
        } catch (error) {
            const err = error instanceof Error ? error : new Error('Worker初始化失败');
            this.options.onError?.(err);
        }
    }

    // 处理Worker消息
    private handleMessage(message: WorkerMessage) {
        const { id, type, data, error } = message;
        const task = this.pendingTasks.get(id);

        if (!task) return;

        switch (type) {
            case 'result':
                task.resolve(data);
                this.pendingTasks.delete(id);
                break;
            case 'error':
                task.reject(error || new Error('Worker任务执行失败'));
                this.pendingTasks.delete(id);
                break;
        }
    }

    // 发送任务到Worker（返回Promise）
    postTask<T = any, R = any>(data: T): Promise<R> {                
        if (this.isTerminated || !this.worker) {
            return Promise.reject(new Error('Worker已终止或未初始化'));
        }

        const taskId = generateTaskId();        
        return new Promise((resolve, reject) => {
            this.pendingTasks.set(taskId, { resolve, reject });
            
            // 发送任务消息
            this.worker!.postMessage({
                id: taskId,
                type: 'task',
                data
            } as WorkerMessage<T>);            

            // 超时处理（可选，避免任务无限挂起）
            setTimeout(() => {
                if (this.pendingTasks.has(taskId)) {
                    const err = new Error('Worker任务超时');
                    reject(err);
                    this.pendingTasks.delete(taskId);
                }
            }, 300000); // 30秒超时
        });
    }

    // 终止Worker
    terminate() {
        if (this.isTerminated || !this.worker) return;

        this.worker.terminate();
        this.worker = null;
        this.isTerminated = true;
        this.pendingTasks.forEach(({ reject }) => reject(new Error('Worker已终止')));
        this.pendingTasks.clear();
        this.options.onTerminate?.();
    }

    // 检查Worker是否活跃
    isActive() {
        return !this.isTerminated && !!this.worker;
    }
}